package com.niit.user.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author yaojianfeng
 */
@Slf4j
@RestController
@RequestMapping("/hystrix")
public class HystrixProviderController {
    /**
     * 自动注入端口号的值,方便区分查看应用
     */
    @Value("${server.port}")
    private String port;

    @GetMapping("{param}")
    public String showInfo(@PathVariable("param")String param){
        return "当前应用的端口是: " + port+ "传递过来的参数是: "+ param;
    }

    /**
     * 使用随机数模拟请求超时断路
     * @param param
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/sleep/{param}")
    public String showInfoWhileSleeping(@PathVariable("param") String param) throws InterruptedException {
        //让处理线程等待几秒钟
        long begin = System.currentTimeMillis();
        int sleepTime = new Random().nextInt(2000);
        Thread.sleep(sleepTime);
        long end = System.currentTimeMillis();
        System.out.println("阻塞时间: " + (end-begin)+"毫秒");
        return "当前应用的端口是: " + port
                + "; 传递过来的参数是: "
                + param + "; 共花费执行时间: "
                + (end - begin) + " 毫秒";
    }


    /**
     * 通过参数控制请求时长,手动模拟超时断路
     * @param param
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/byParam/{param}")
    public String showInfoUseParam(@PathVariable("param") String param) throws InterruptedException {
        //让处理线程等待几秒钟
        long begin = System.currentTimeMillis();
        int sleepTime = Integer.parseInt(param);
        Thread.sleep(sleepTime);
        long end = System.currentTimeMillis();
        System.out.println("阻塞时间: " + (end-begin)+"毫秒");
        return "当前应用的端口是: " + port
                + "; 传递过来的参数是: "
                + param + "; 共花费执行时间: "
                + (end - begin) + " 毫秒";
    }
}
